﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using Cashier_Interface;
using Cashier_Service;
using Cashier.utils;
using Cashier_Utils;

namespace Cashier.purchase
{
    public partial class PurchaseListControl : UserControl, IDataGridViewData, IReloadData, IPrinter
    {
        private MainForm mainform;
        private static PurchaseListControl purchaseListControl;
        private BillPurchaseService purchaseService;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="mainform"></param>
        private PurchaseListControl(MainForm mainform)
        {
            InitializeComponent();
            this.mainform = mainform;
            this.dataGridView1.ImplementsInstance = this;
            this.purchaseService = new BillPurchaseService();

            this.ControlsSetRights();
            this.Dock = DockStyle.Fill;
        }

        /// <summary>
        /// 返回PurchaseListControl实例
        /// </summary>
        /// <param name="mainform"></param>
        /// <returns></returns>
        public static PurchaseListControl GetPurchaseListControl(MainForm mainform)
        {
            if (purchaseListControl == null)
                purchaseListControl = new PurchaseListControl(mainform);
            purchaseListControl.RefreshDataGridViewData();
            return purchaseListControl;
        }

        #region 功能方法实现

        /// <summary>
        /// 控件设置权限
        /// </summary>
        private void ControlsSetRights()
        {
            Button[] buttons = { button_query, button_create };
            RightsforControls.RightsforButton(mainform.Admin.RolePurviewtable, buttons);
            ContextMenuStrip[] menuStrips = { contextMenuStrip_dgv };
            RightsforControls.RightsforContextMenuStrip(mainform.Admin.RolePurviewtable, menuStrips);
        }

        /// <summary>
        /// 查看进货单商品
        /// </summary>
        protected void ViewPurchaseGoods()
        {
            if (this.dataGridView1.SelectedRows.Count > 0)
            {
                String purchaseno = this.dataGridView1.SelectedRows[0].Cells["purchase_no"].Value.ToString();
                PurchaseGoodsListControl purchaseGoodsListControl = PurchaseGoodsListControl.GetPurchaseGoodsListControl(mainform, purchaseno);
                mainform.AddDataGridViewPanelControl(purchaseGoodsListControl);
            }
        }

        /// <summary>
        /// 删除进货单
        /// </summary>
        protected void DeletePurchase()
        {
            if (this.dataGridView1.SelectedRows.Count > 0)
            {
                DialogResult result = MessageBox.Show("确定要删除选中数据吗？", "提示", MessageBoxButtons.YesNo);
                if (result == DialogResult.Yes)
                {
                    StringBuilder sb = new StringBuilder();
                    foreach (DataGridViewRow row in this.dataGridView1.SelectedRows)
                    {
                        sb.Append(row.Cells["purchase_no"].Value.ToString()).Append(",");
                    }
                    sb.Remove(sb.Length - 1, 1);
                    int count = this.purchaseService.DeleteBillPurchase(sb.ToString());
                    if (count > 0)
                    {
                        MessageBox.Show("删除成功！");
                        this.RefreshDataGridViewData();
                    }
                    else
                        MessageBox.Show("删除失败！");
                }
            }
        }

        #endregion

        #region IDataGridViewData 成员

        void IDataGridViewData.EnterkeyEventHandler()
        {
            this.ViewPurchaseGoods();
        }

        void IDataGridViewData.GenerateGridViewColumns(DataGridView dgv)
        {
            this.dataGridView1.AutoGenerateColumns = false;
            this.dataGridView1.Columns.Clear();
            this.dataGridView1.Columns.Add(GenearteDataGridViewColumn.GetDataGridViewDataFieldColumn("id", null, true, 0, null, null, false, false));
            this.dataGridView1.Columns.Add(GenearteDataGridViewColumn.GetDataGridViewDataFieldColumn("purchase_no", "进货单号", true, 16, ActKey.LEFT, ActKey.LEFT, true, false));
            this.dataGridView1.Columns.Add(GenearteDataGridViewColumn.GetDataGridViewDataFieldColumn("numbers", "商品数量", true, 6, ActKey.RIGHT, ActKey.RIGHT, true, false));
            this.dataGridView1.Columns.Add(GenearteDataGridViewColumn.GetDataGridViewDataFieldColumn("goods_total", "商品金额", true, 6, ActKey.RIGHT, ActKey.RIGHT, true, false));
            this.dataGridView1.Columns.Add(GenearteDataGridViewColumn.GetDataGridViewDataFieldColumn("discount_total", "优惠金额", true, 6, ActKey.RIGHT, ActKey.RIGHT, true, false));
            this.dataGridView1.Columns.Add(GenearteDataGridViewColumn.GetDataGridViewDataFieldColumn("purchase_total", "货单金额", true, 6, ActKey.RIGHT, ActKey.RIGHT, true, false));
            this.dataGridView1.Columns.Add(GenearteDataGridViewColumn.GetDataGridViewDataFieldColumn("fare", "运费", true, 6, ActKey.RIGHT, ActKey.RIGHT, true, false));
            this.dataGridView1.Columns.Add(GenearteDataGridViewColumn.GetDataGridViewDataFieldColumn("other_cost", "其它费用", true, 6, ActKey.RIGHT, ActKey.RIGHT, true, false));
            this.dataGridView1.Columns.Add(GenearteDataGridViewColumn.GetDataGridViewDataFieldColumn("count_total", "金额总计", true, 6, ActKey.RIGHT, ActKey.RIGHT, true, false));
            this.dataGridView1.Columns.Add(GenearteDataGridViewColumn.GetDataGridViewDataFieldColumn("amin_name", "进货人", true, 9, ActKey.CENTER, ActKey.CENTER, true, false));
            this.dataGridView1.Columns.Add(GenearteDataGridViewColumn.GetDataGridViewDataFieldColumn("purchase_date", "进货日期", true, 9, ActKey.CENTER, ActKey.CENTER, true, false));           
            this.dataGridView1.Columns.Add(GenearteDataGridViewColumn.GetDataGridViewDataFieldColumn("debt_amount", "欠款金额", true, 6, ActKey.RIGHT, ActKey.RIGHT, true, false));
            this.dataGridView1.Columns.Add(GenearteDataGridViewColumn.GetDataGridViewDataFieldColumn("supplier_name", "供货商", true, 9, ActKey.LEFT, ActKey.LEFT, true, false));
            this.dataGridView1.Columns.Add(GenearteDataGridViewColumn.GetDataGridViewDataFieldColumn("note", "备注", true, 9, ActKey.CENTER, ActKey.CENTER, true, false));
        }

        void IDataGridViewData.GetBindingData(int rowindex, int pageindex, int pagesize)
        {
            try
            {
                String enterpriseNo = mainform.Admin.EnterpriseNo;
                String purchaseno = textbox_purchaseno.Text.Trim();
                String supplierno = String.Empty;
                String adminUsername = mainform.UsernameForQuery;
                String startdate = String.Empty;
                String enddate = String.Empty;
                if (dateTimePicker_startdate.Checked && dateTimePicker_enddate.Checked &&
                    dateTimePicker_enddate.Value.CompareTo(dateTimePicker_startdate.Value) >= 0)
                {
                    startdate = dateTimePicker_startdate.Value.ToShortDateString();
                    enddate = dateTimePicker_enddate.Value.ToShortDateString();
                }

                DataTable dt = purchaseService.GetBillPurchaseTable(pageindex, pagesize, enterpriseNo, null, purchaseno, supplierno, adminUsername, startdate,
                    enddate, 0M, null, "id");
                this.dataGridView1.DataSource = dt;
                if (dt != null && dt.Rows.Count > 0)
                {
                    if (rowindex > 0)
                        dataGridView1.Rows[0].Selected = false;
                    dataGridView1.Rows[rowindex].Selected = true;
                }
                dataGridView1.Columns[0].Visible = false;

                mainform.SetPageInfo(dataGridView1.Recordcount, pageindex, pagesize);
            }
            catch (Exception ex)
            {
                LogsUtil.Record(ex);
            }
        }

        long IDataGridViewData.GetBindingDataRecord()
        {
            long record = 0;
            try
            {
                String enterpriseNo = mainform.Admin.EnterpriseNo;
                String purchaseno = textbox_purchaseno.Text.Trim();
                String supplierno = String.Empty;
                String adminUsername = mainform.UsernameForQuery;
                String startdate = String.Empty;
                String enddate = String.Empty;
                if (dateTimePicker_startdate.Checked && dateTimePicker_enddate.Checked &&
                    dateTimePicker_enddate.Value.CompareTo(dateTimePicker_startdate.Value) >= 0)
                {
                    startdate = dateTimePicker_startdate.Value.ToShortDateString();
                    enddate = dateTimePicker_enddate.Value.ToShortDateString();
                }

                record = purchaseService.GetBillPurchaseRecord(enterpriseNo, null, purchaseno, supplierno, adminUsername, startdate, enddate, 0M);
            }
            catch (Exception ex)
            {
                LogsUtil.Record(ex);
            }
            return record;
        }

        #endregion

        #region 刷新数据

        /// <summary>
        /// 刷新数据
        /// </summary>
        public void RefreshDataGridViewData()
        {
            this.dataGridView1.LoadingData();
        }

        #endregion


        #region 重写方法

        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            bool b = base.ProcessCmdKey(ref msg, keyData);
            if (keyData == Keys.Up || keyData == Keys.Down)
            {
                this.dataGridView1.Focus();
            }
            else if (keyData == Keys.F8)
                this.RefreshDataGridViewData();
            else if (keyData == Keys.F9)
            {
                PurchaseAddForm purchaseAddForm = PurchaseAddForm.GetPurchaseAddForm(this.mainform, this);
                purchaseAddForm.Show();
            }
            return b;
        }

        #endregion

        #region 控件事件

        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button_query_Click(object sender, EventArgs e)
        {
            this.RefreshDataGridViewData();
        }

        /// <summary>
        /// 新建
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button_create_Click(object sender, EventArgs e)
        {
            PurchaseAddForm purchaseAddForm = PurchaseAddForm.GetPurchaseAddForm(this.mainform, this);
            purchaseAddForm.Show();
        }

        /// <summary>
        /// 查看进货商品
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripMenuItem_view_Click(object sender, EventArgs e)
        {
            this.ViewPurchaseGoods();
        }

        /// <summary>
        /// 删除进货单
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripMenuItem_delete_Click(object sender, EventArgs e)
        {
            this.DeletePurchase();
        }

        /// <summary>
        /// 单元格双击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            this.ViewPurchaseGoods();
        }

        #endregion

        #region IReloadData 成员

        void IReloadData.ReloadDataGridViewData(object param)
        {
            this.RefreshDataGridViewData();
        }

        #endregion


        #region IPrinter 成员

        DataGridView IPrinter.GetAllRows()
        {
            try
            {
                ((IDataGridViewData)this).GetBindingData(0, 0, 0);
            }
            catch (Exception ex)
            {
                LogsUtil.Record(ex);
            }
            return this.dataGridView1;
        }

        DataGridView IPrinter.GetSelectedRows()
        {
            return this.dataGridView1;
        }

        void IPrinter.VisibleColumn(string columnname)
        {
            try
            {
                if (this.dataGridView1.Columns[columnname].Visible)
                    this.dataGridView1.Columns[columnname].Visible = false;
                else
                    this.dataGridView1.Columns[columnname].Visible = true;
            }
            catch (Exception ex)
            {
                LogsUtil.Record(ex);
            }
        }

        #endregion
    }
}
